package com.gexiaobao.pigeon.ui.fragment.mine.organization.detail

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.LinearLayout
import android.widget.ListPopupWindow
import android.widget.TextView
import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initFooter
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentPigeonReceiptBinding
import com.gexiaobao.pigeon.ui.adapter.AdapterReceiptPigeon
import com.gexiaobao.pigeon.ui.adapter.MyAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogMemberInfo
import com.gexiaobao.pigeon.viewmodel.OrgDetailViewModel
import com.gexiaobao.pigeon.viewmodel.SharedViewModel
import com.kingja.loadsir.core.LoadService
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat


/**
 * @Author      : hxw
 * @Date        : 2024/5/23 15:50
 * @Describe    : 收鸽清单
 */
class FragmentPigeonReceipt : BaseFragment<OrgDetailViewModel, FragmentPigeonReceiptBinding>() {

    private var viewHeader: View? = null
    private val mAdapter: AdapterReceiptPigeon by lazy { AdapterReceiptPigeon(arrayListOf()) }
    private var mRaceId = 0
    private lateinit var loadSir: LoadService<Any>
    private var ringId = ""
    private var memberName = ""
    private var listPopupWindow: ListPopupWindow? = null
    private val mList: MutableList<String> = mutableListOf()
    private var mSearchType = ""

    private lateinit var editQuery: AppCompatEditText
    private lateinit var ivClose: AppCompatImageView
    private lateinit var tvSearchType: AppCompatTextView
    private lateinit var llSearchType: LinearLayout
    private lateinit var tvSearch: TextView
    private lateinit var tvReceiptPigeonNum: AppCompatTextView

    private var viewModel: SharedViewModel? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        viewModel = ViewModelProvider(requireActivity())[SharedViewModel::class.java]
        viewModel?.orgInfoBean?.observe(viewLifecycleOwner) {
            if (it != null) {
                mRaceId = it.raceId
                onRefresh(true)
            }
        }
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    @SuppressLint("MissingInflatedId")
    override fun initView(savedInstanceState: Bundle?) {
        mSearchType = getString(R.string.search_by_foster)
        loadSir = loadServiceInit(mDatabind.includeList.swipeRefreshLayout) {
            onRefresh(true)
        }

        mDatabind.includeList.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter).let {
            it.addItemDecoration(SpaceItemDecoration(0, 0))
            it.initFooter {
                //触发加载更多时请求数据
                mViewModel.getLoftPigeonListByRaceId(false, memberName, ringId, mRaceId)
            }
        }

        mDatabind.includeList.swipeRefreshLayout.init {
            onRefresh(true)
        }

        mDatabind.includeList.swipeRefreshLayout.isEnabled = false

        viewHeader = LayoutInflater.from(context).inflate(R.layout.header_receipt_pigeon, null)
        editQuery = viewHeader!!.findViewById(R.id.editQuery)
        ivClose = viewHeader!!.findViewById(R.id.ivClose)
        tvSearchType = viewHeader!!.findViewById(R.id.tvSearchType)
        llSearchType = viewHeader!!.findViewById(R.id.llSearchType)
        tvSearch = viewHeader!!.findViewById(R.id.tvSearch)
        tvReceiptPigeonNum = viewHeader!!.findViewById(R.id.tvReceiptPigeonNum)

        initPopup()

        mAdapter.addChildClickViewIds(R.id.tvReceiptName)
        mAdapter.setOnItemChildClickListener { _, _, position ->
            showMemberInfoDialog(
                mAdapter.data[position].memberName,
                mAdapter.data[position].shedNo,
                mAdapter.data[position].pigeonsCountWithMemberId,
            )
        }

        editQuery.addTextChangedListener {
            ivClose.isVisible = it.toString().isNotEmpty()
        }

        editQuery.setOnEditorActionListener { _, i, _ ->
            when (i) {
                EditorInfo.IME_ACTION_SEARCH -> {
                    searchResultData()
                    hideSoftKeyboard(activity)
                }

                else -> {}
            }
            false
        }

        listPopupWindow?.setOnItemClickListener { _, _, position, _ ->
            mSearchType = mList[position]
            tvSearchType.text = mSearchType
            mList.add(0, mList.removeAt(position))
            listPopupWindow!!.dismiss()
        }
    }

    private fun searchResultData() {
        if (mSearchType == "搜鸽主") {
            editQuery.text.toString().trim()
            ringId = ""
        } else {
            ringId = editQuery.text.toString().trim()
            memberName = ""
        }
        onRefresh(true)
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(ivClose, llSearchType, tvSearch) {
            when (it) {
                tvSearch -> searchResultData()
                llSearchType -> listPopupWindow?.show()
                ivClose -> {
                    editQuery.setText("")
                    memberName = ""
                    ringId = ""
                    onRefresh(true)
                }
            }
        }
    }

    private fun initPopup() {
        mList.add(getString(R.string.search_by_foster))
        mList.add(getString(R.string.search_by_ringId))

        /** 初始化ListPopupWindow，适配 */
        listPopupWindow = context?.let { ListPopupWindow(it) }
        val adapter = MyAdapter(context, mList)
        listPopupWindow?.setAdapter(adapter)
        listPopupWindow?.anchorView = llSearchType//设置ListPopupWindow的锚点，关联mButton位置
        listPopupWindow?.width = LinearLayout.LayoutParams.WRAP_CONTENT
        listPopupWindow?.height = LinearLayout.LayoutParams.WRAP_CONTENT
        listPopupWindow?.isModal = true
    }

    private fun onRefresh(b: Boolean) {
        showLoading(getString(R.string.loading))
        mViewModel.getLoftPigeonListByRaceId(b, memberName, ringId, mRaceId)
    }

    @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /** 收鸽清单 */
        mViewModel.receiptPigeonResult.observe(viewLifecycleOwner) {
            if (!it.isEmpty) {
                mAdapter.addHeaderView(viewHeader!!)
            }
            tvReceiptPigeonNum.text = getString(R.string.Number_of_pigeon_feathers_collected) + ":  " + it.total.toString() + getString(R.string.yu)
            loadListData(it, mAdapter, loadSir, mDatabind.includeList.swipeRecyclerView, mDatabind.includeList.swipeRefreshLayout)
        }
    }

    private fun showMemberInfoDialog(memberName: String, memberNo: String, pigeonNumber: Int) {
        val dialog = RxDialogMemberInfo(context)
        dialog.setMemberName("$memberNo - $memberName")
        dialog.setSendPigeonNum(getString(R.string.Number_of_pigeon) + "： $pigeonNumber")
        dialog.setFullScreenWidth()
        dialog.show()
    }

    companion object {
        fun newInstance(): FragmentPigeonReceipt {
            return FragmentPigeonReceipt()
        }
    }
}